<template>
  <div>
    <HeaderTop></HeaderTop>
    <el-row type="flex" justify="center">
      <el-col :span="18">
        <h2>文章修改</h2>
      </el-col>
    </el-row>
    <el-row type="flex" justify="center">
      <el-col :span="18">
        <!--文章标题-->
        <el-input
            placeholder="请输入标题"
            v-model="article.title"
            clearable>
        </el-input>
        <!--文章简介-->
        <el-input
            type="textarea"
            :rows="3"
            placeholder="请输入简介"
            v-model="article.summary"
            clearable
            style="margin-top: 30px">
        </el-input>
        <!--文章分类-->
        <el-form ref="form" :model="form" style="margin-top: 30px">
          <div style="float: left;width: 300px">
            <el-form-item label="所属板块" >
              <el-select v-model="form.boardName" placeholder="请选择"  @change="changeSelect">
                <el-option
                    v-for="(item,index) in boardOptions"
                    :key="index"
                    :label="item"
                    :value="item"
                />
              </el-select>
            </el-form-item>
          </div>
         <div style="float: left;width: 300px">
           <el-form-item label="文章分类">
             <el-select v-model="form.categoryId"  placeholder="请选择分类">
               <el-option
                   v-for="(item,index) in categoryOptions"
                   :key="index"
                   :label="item.name"
                   :value="item.id"
               />
             </el-select>
           </el-form-item>
         </div>

        </el-form>


        <MyEditor v-bind:htmlContent="article.body.contenthtml" ref="myEditor" style="margin-top: 120px"></MyEditor>
        <!--文章标签-->
        <div style="margin-top: 30px">
          给文章添加标签:&nbsp;&nbsp;
          <el-tag :key="tag.id"
                  v-for="tag in dynamicTags"
                  closable :disable-transitions="false"
                  @click="changeValue(tag)"
                  @close="handleClose(tag)">
            {{tag.name}}
          </el-tag>

          <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small"
                    @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>

        </div>
        <el-button type="primary" style="margin:20px 0 60px 600px" @click="modifyArticle(2)">发 布</el-button>
        <el-button type="primary" style="margin:20px 0 60px 60px" @click="modifyArticle(0)">存草稿</el-button>

      </el-col>
    </el-row>
  </div>

</template>

<script>
import MyEditor from "@/components/MyEditor";
import { reactive } from "vue";
import HeaderTop from "@/components/HeaderTop";
export default {
  name: "ModifyArticle",

  components:{MyEditor,HeaderTop},
  data(){
    return{
      dynamicTags: [],
      inputVisible: false,
      inputValue: '',
      // tempTag: '',
      // 是否是重复数据
      isRepeatedData: false,
      // 是否改变原来的值
      isChange: false,
      editTag:{},
      articleId:0,
      boardName:'',
      html:"",
      article:{

      },
      boardOptions: [],
      boardList: {},
      categoryOptions: [],
      form: {
        boardName: '',
        categoryId: ''
      },
    }
  },
  methods:{
    handleClose(tag) {
      //发送删除tag的axios请求
      let url = 'tag/deleteById/'+tag.id;
      this.$axios.delete(url)
          .then(res=>{
            if(res.data.code == 200){
              this.$message.success('删除成功');
            }else{
              this.$message.error('删除失败');
            }
          })
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },

    showInput() {
      this.tempTag = ''
      this.inputVisible = true;
      this.inputValue = ''
      this.isChange = false

      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      this.isRepeatedData = false
      let inputValue = this.inputValue;
      // 去空格
      inputValue = inputValue.replace(/^\s\s*/, '').replace(/\s\s*$/, '')
      if (inputValue == '') {
        this.inputVisible = false
        return
      }
      // console.log(inputValue+'uuu:'+this.tempTag)
      // 判断新增的值是否重复
      let oldTags = [];
      for(let t of this.dynamicTags){
        oldTags.push(t.name)
      }
      if (oldTags.indexOf(inputValue) != -1) {
        this.isRepeatedData = true
        this.$message.warning("该标签已经存在！")
        return
      } else {
        this.isRepeatedData = false
        // this.isChange = false
      }
      // 判断是否修改原有值，是 替换修改好的值，否新增
      if (this.isChange) {
        let index = -1;
        for (let t of this.dynamicTags){
          if(t.id == this.editTag.id){
            index = this.dynamicTags.indexOf(t);
          }
        }
        this.editTag.name = this.inputValue;
        console.log(this.editTag)
        // console.log(index);
        //在这里发送修改标签的axios请求
        let url = 'tag/modifyTag'
        this.$axios.post(url,this.editTag)
            .then(res=>{
          if(res.data.code == 200){
              this.getArticleTags();
          }
        })

        this.dynamicTags[index] = this.editTag;
        this.inputVisible = false
        return
      }
      // 点击添加时，追加
      if (inputValue) {
        //这里发送添加的axios请求，获得新添加的tag的id  这里的15就是新添加的tag的id
        let url = 'tag/addTag';
        console.log()
        this.$axios.post(url,null,{
              params:{
                articleId:this.articleId,
                userId:this.article.user.id,
                tagName:inputValue,
              }
            }
          ).then(res=>{
          if(res.data.code == 200){
            this.$message.success('添加标签成功')
            this.getArticleTags();
          }
        })
        // this.dynamicTags.push({id:15,name:inputValue});
        // console.log(inputValue+'tt:'+this.dynamicTags)
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
    //修改标签值的方法
    changeValue(tag) {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
      this.inputValue = tag.name
      this.editTag= tag;
      // console.log(this.editTag)
      // this.tempTag = tag.name
      this.isChange = true
    },
    changeSelect() {
      console.log('------------>')
      // 清空分类内容
      this.form.categoryId = ''
      // 遍历板块的下拉选项数组
      for (const k in this.boardOptions) {
        // 板块内容 是否等于 板块的下拉选择数组中的某一项
        if (this.form.boardName === this.boardOptions[k]) {
          for (let b of this.boardList){
            if(this.form.boardName == b.name){
              this.categoryOptions = b.categories;
            }
          }
        }
      }
    },
    //获得板块以及分类列表的方法
    getBoardAndCategoryList(){
      let url = 'board/getBoardAndCategory'
      this.$axios.get(url)
          .then(res=>{
            this.boardList = res.data.data;
            for(let b of this.boardList){
              this.boardOptions.push(b.name)
            }
            console.log(this.boardList);
          })
    },
    getArticle() {
      //这里发送axios的请求，获得文章的信息
      let url = "article/getArticleById";
      this.$axios.get(url,{
        params:{
          id:this.articleId
          }
        })
          .then(res=>{
            if(res.data.code == 200){
              this.article = res.data.data;
              this.html = this.article.body.contenthtml;
              this.getArticleBoardName(this.article.category.id);
            }
          })
    },
    //获得文章所在板块的方法
    getArticleBoardName(categoryId){
      let url = 'board/getBoardNameByCateId';
       this.$axios.get(url,{
         params:{
           categoryId:categoryId
         }
       }).then(res=>{
         console.log("2222"+res.data.data)
         this.boardName = res.data.data;
         this.form.boardName = this.boardName;
         this.changeSelect();
         this.form.categoryId = parseInt(this.article.category.id);
       })

    },
    //获得文章标签的方法
    getArticleTags(){
      let url = 'article/getArticleTags';
      this.$axios.get(url,{
        params:{
          articleId:this.articleId
        }
      }).then(res=>{
          this.dynamicTags = res.data.data;
      })
    },
    //修改文章的方法
    modifyArticle(status){
      this.article.categoryId = this.form.categoryId;
      this.article.category.id = this.form.categoryId;
      this.article.status = status;
      this.article.body.contenthtml = this.$refs.myEditor.getEditorHtml();
      console.log(this.article);
      //发送axios请求
      let url = 'article/modifyArticle'
      this.$axios.post(url,this.article)
          .then(res=>{
            if(res.data.code == 200){
              this.$message.success("修改成功~")
            }else{
              this.$message.error("修改失败！")
            }
          })
    },
  },
  created() {
    this.articleId = this.$route.query.articleId;
    this.getArticle();
    this.getBoardAndCategoryList();
    this.getArticleTags();
  },

}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>